package com.ly.wxstore.utils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springside.modules.utils.PropertiesLoader;

public class ServerPathUtils {
	
	private static Logger logger = LoggerFactory.getLogger(ServerPathUtils.class);
	
	private static ApplicationContext applicationContext;
	private static PropertiesLoader propertiesLoader;
	
	private static String baseImageDir=null;
	
	
	public static void init(ServletContext ctx){
		applicationContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
		
		String[] profileNames = applicationContext.getEnvironment().getActiveProfiles();
		
		String[] defaultProfileNames = applicationContext.getEnvironment().getDefaultProfiles();
		
		if(profileNames.length==0 && defaultProfileNames.length == 0){
			logger.error("系统启动失败：请设置spring配置文件。");
		}
		
		if(profileNames.length > 0){
			propertiesLoader = new PropertiesLoader("classpath:/application-"+profileNames[0]+".properties");
		}else if(defaultProfileNames.length > 0){
			propertiesLoader = new PropertiesLoader("classpath:/application-"+defaultProfileNames[0]+".properties");
		}
		else{
			logger.error("系统启动失败：请设置spring配置文件。");
			propertiesLoader = new PropertiesLoader("classpath:/application.properties");
		}
			
		baseImageDir = propertiesLoader.getProperty("base.image.dir");
		
		logger.info("init baseImageDir:"+baseImageDir);
	}

	/**
	 * base.image.dir
	 * @param request
	 * @return
	 */
	public static String getImageDir(MultipartHttpServletRequest request) {
		if(baseImageDir ==null){
			init(request.getSession().getServletContext());
		}
		
		return baseImageDir;
	}
	
	/**
	 * base.image.dir
	 * @param request
	 * @return
	 */
	public static String getImageDir(HttpServletRequest request) {
		if(baseImageDir ==null){
			init(request.getSession().getServletContext());
		}
		return baseImageDir ;
	}
	
}
